//  自定义玩法 抽奖内容 对象
const otherPlayObj = {
    "奖项名称": "幸运随机奖",
    "奉献者": "",
    "总额": 5000,
    "分派数量": 5,
}
// 自定义玩法的 中奖结果
let otherWinningResults = []
/**
 * 进入自定义玩法
 * @param participator 参与者名称集合
 * */
function enterOtherPlay(participator) {
    const mainDiv = $('#main_div')
    // 清空主Div
    $(mainDiv).empty();
    // 添加返回按钮
    const homeBtn = $('<span class="homeBtn2">返回首页</span>')
    $(homeBtn).click(function (e) {
        e.preventDefault()
        $.confirm({
            title: '返回首页',
            content: '返回首页将丢失已获奖人员名单,是否返回?',
            animation: "scale",
            backgroundDismiss: true,
            buttons: {
                "返回首页": function () {
                    //  重置 参数 并重新加载页面
                    over = false
                    starting = false
                    load = true
                    location.reload()
                },
                "取 消": () => {
                }
            }
        });
    })
    // 添加特定class
    $('#main').addClass('startDivClass')
    // 创建 表单 盒子
    const formClassBox = $('<div class="formClassBox"></div>')
    // 创建表单div
    const formDiv = $('<div class="formClass"></div>')
    //  遍历 自定义奖项 的属性 并生成 input
    for (let otherPlayObjKey in otherPlayObj) {
        const label_input = $('<div class="label_input_div"></div>')
        const label = $(`<label class="label">${otherPlayObjKey}<label>`)
        const input = $(`<input class="input" value="${otherPlayObj[otherPlayObjKey]}" name="${otherPlayObjKey}"><label>`)
        $(label_input).append($(label))
        $(label_input).append($(input))
        $(formDiv).append($(label_input))
    }
    $(formClassBox).append(formDiv)
    $(formClassBox).append(homeBtn)
    $(mainDiv).append(formClassBox)
    //  创建OK按钮
    const okBtn = $(`<button class="okBtn">OK</button>`)
    $(formDiv).append(okBtn)
    const resultDiv = $(`<div class="allResult"></div>`)
    // 添加左下角的 中奖人员信息
    const link = $(`<span style="font-size: 1.8rem;text-decoration: underline">已中奖人员:</span>`)
    $(resultDiv).append(link)
    // 点击左下角链接 跳转到结果显示
    $(link).click(function () {
        //  创建结果div
        const div = $('<div class="allResultBox"></div>')
        $(mainDiv).addClass('allResultBoxParent')
        $(mainDiv).append(div)
        for (let otherWinningResult of otherWinningResults) {
            const name = otherWinningResult.name
            const nameDiv = $(`<h1 class="nameDiv">${name}</h1>`)
            const consecrated = otherWinningResult.consecrated
            const consecratedDiv = $(`<div class="consecratedDiv"><span style="width: 13rem;text-align: right;display: inline-block">奖金出资人:&nbsp;&nbsp;</span><span class="consecratedDiv_staffName">${consecrated}</span></div>`)
            const total = otherWinningResult.total
            const totalDiv = $(`<div class="totalDiv"><span style="width: 13rem;text-align: right;display: inline-block">总金额:&nbsp;&nbsp;</span>${total}元</div>`)
            const frequency = otherWinningResult.frequency
            const frequencyDiv = $(`<div class="frequencyDiv"><span style="width: 13rem;text-align: right;display: inline-block">分派数量:&nbsp;&nbsp;</span>${frequency}位</div>`)
            const staffBox = $('<div class="staffBox"></div>')
            for (let winner of otherWinningResult.winners) {
                $(staffBox).append($(`<span class="staffSpan">${winner}</span>`))
            }

            $(div).append(nameDiv, consecratedDiv, totalDiv, frequencyDiv, staffBox)
        }
        const closeBtn = $(`<span class="closeBtn">x</span>`)
        $(mainDiv).append(closeBtn)
        let temp_si = setInterval(() => {
            const documentHeight = $(div).innerHeight();
            const scrollHeight = $(div)[0].scrollHeight;
            if (scrollHeight <= documentHeight + 10) {
                return
            }
            let top = $(div).scrollTop()
            $(div).scrollTop(Number.parseInt(top) + 1)
            console.log("top", top)
            console.log("documentHeight", documentHeight)
            console.log("scrollHeight", scrollHeight)
            if (top + documentHeight >= scrollHeight - 10) {
                if (top >= 1800) {
                    (div).empty()
                }
                $(div).append(`<hr class="resultHrClass" />`)
                for (let otherWinningResult of otherWinningResults) {
                    const name = otherWinningResult.name
                    const nameDiv = $(`<h1 class="nameDiv">${name}</h1>`)
                    const consecrated = otherWinningResult.consecrated
                    const consecratedDiv = $(`<div class="consecratedDiv"><span style="width: 13rem;text-align: right;display: inline-block">奖金出资人:&nbsp;&nbsp;</span><span class="consecratedDiv_staffName">${consecrated}</span></div>`)
                    const total = otherWinningResult.total
                    const totalDiv = $(`<div class="totalDiv"><span style="width: 13rem;text-align: right;display: inline-block">总金额:&nbsp;&nbsp;</span>${total}元</div>`)
                    const frequency = otherWinningResult.frequency
                    const frequencyDiv = $(`<div class="frequencyDiv"><span style="width: 13rem;text-align: right;display: inline-block">分派数量:&nbsp;&nbsp;</span>${frequency}位</div>`)
                    const staffBox = $('<div class="staffBox"></div>')
                    for (let winner of otherWinningResult.winners) {
                        $(staffBox).append($(`<span class="staffSpan">${winner}</span>`))
                    }
                    $(div).append(nameDiv, consecratedDiv, totalDiv, frequencyDiv, staffBox)
                }
            }
        }, 30)
        $(closeBtn).click(function () {
            $(closeBtn).remove()
            $(div).remove()
            clearInterval(temp_si)
        })

    })
    const staff_list = []
    for (let otherWinningResult of otherWinningResults) {
        const winners = otherWinningResult.winners
        for (let winner of winners) {
            staff_list.push(winner)
        }
    }

    function addWinner(staff_list, resultDiv) {
        if (staff_list.length === 0) {
            return
        }
        const staff = staff_list[0]
        const length = staff_list.filter(sl => sl === staff_list[0]).length
        if (length <= 1) {
            $(resultDiv).append($(`<span class="allResultItem">${staff}</span>`))
        } else {
            $(resultDiv).append($(`<span class="allResultItem">${staff + `(${length})`}</span>`))
        }
        while (staff_list.indexOf(staff) >= 0) {
            staff_list.splice(staff_list.indexOf(staff), 1)
        }
        addWinner(staff_list, resultDiv)
    }

    addWinner(staff_list, resultDiv)
    $(formClassBox).append(resultDiv)
    //抽奖倒计时
    let countdownTime = 3

    function otherItemFunc(nameOfTheAward, start_frequency, frequency, consecrated, total, winningResult) {
        (mainDiv).empty()
        const boxDiv = $('<div class="boxDiv"></div>')
        $(mainDiv).append(boxDiv)
        const raffleCards = $('<div class="raffleCards">????</div>')
        const left = $('<div class="leftDiv"></div>')
        $(left).append(raffleCards)
        $(boxDiv).append(left)
        const right = $('<div class="rightDiv"></div>')
        const otherTitle = $(`<h1 class="otherTitle">${nameOfTheAward} 第${start_frequency}/${frequency}次</h1>`)
        const otherSubTitle = $(`<h2 class="otherSubTitle">${consecrated ? (consecrated + '加码:') : ''} 现金红包大奖总计${total}元,单个奖金:${total / frequency}元</h2>`)
        const otherStartBtn = $('<button class="otherStartBtn">启动</button>')
        $(right).append(otherTitle, otherSubTitle, otherStartBtn)
        $(boxDiv).append(right)
        let tmp_flag = false
        $(otherStartBtn).click(function () {
            if (participator.length === 0) {
                $.confirm({
                    title: '重新载入人员',
                    content: '所有人员均已经中奖,是否重新加入所有人员?',
                    animation: "scale",
                    backgroundDismiss: true,
                    buttons: {
                        "重新加载": function () {
                            participator = JSON.parse(JSON.stringify(staffs))
                            const pp_index = participator.findIndex(pp => pp === consecrated)
                            if (pp_index >= 0) {
                                participator.splice(pp_index, 1)
                            }
                        },
                        "取 消": () => {
                            tmp_flag = true
                            $.alert({title: "提示", content: "无可参与人员"})
                        }
                    }
                });
            }
            if (tmp_flag) {
                return
            }
            let temp = setInterval(() => {
                const text = participator[Math.floor(Math.random() * participator.length)]
                $(raffleCards).text(text)
            }, 20)
            $(otherStartBtn).text('正在抽奖')
            $(mainDiv).addClass('redEnvelopeRain')
            let time = countdownTime
            const countdown = $('<div class="countdown"></div>')
            const yjAudio = $("#yjAudio").get(0)
            yjAudio.currentTime = 0
            yjAudio.play()
            $(mainDiv).append(countdown);
            let i = setInterval(function () {
                if (time === 0) {
                    $("#yjAudio")[0].pause()
                    clearInterval(temp)
                    clearInterval(i)
                    $(mainDiv).removeClass('redEnvelopeRain')
                    $(countdown).remove()
                    const resultDivBox = $(`<div class="resultDivBoxClass"></div>`)
                    const result = $(`<div class="resultDivClass"></div>`)
                    $(resultDivBox).append(result)
                    const text = participator[Math.floor(Math.random() * participator.length)]
                    $(raffleCards).text(text)
                    $(result).text(text)
                    $(mainDiv).append(resultDivBox)
                    $("#yhAudio")[0].play()
                    winningResult.winners.push(text)
                    const ss_index = participator.findIndex(ss => ss === text)
                    if (ss_index >= 0) {
                        participator.splice(ss_index, 1)
                    }
                    let t_i = 1
                    let si2 = setInterval(() => {
                        if (t_i === 0) {
                            clearInterval(si2)
                            let str = '点击继续抽奖'
                            if (start_frequency >= frequency) {
                                str = '已结束,点击完成'
                                otherWinningResults.push(winningResult)
                                localStorage.setItem('otherWinningResults', JSON.stringify(otherWinningResults))
                            }
                            const goOn = $(`<span class="goOnClass">${str}</span>`)
                            $(result).append(goOn)
                            $(goOn).click(function () {
                                $("#yhAudio")[0].pause()
                                $(resultDivBox).remove()
                                if (start_frequency >= frequency) {
                                    enterOtherPlay(participator)
                                } else {
                                    start_frequency++
                                    otherItemFunc(nameOfTheAward, start_frequency, frequency, consecrated, total, winningResult)
                                }
                            })
                        }
                        t_i--
                    }, 800)
                }
                countdown.text(time)
                time--
            }, 800)
        })
    }

    $(okBtn).click(function () {
        const nameOfTheAward = $("input[name=奖项名称]").val()
        const consecrated = $("input[name=奉献者]").val()
        const total = Number.parseInt($("input[name=总额]").val())
        const frequency = Number.parseInt($("input[name=分派数量]").val())
        $(mainDiv).empty();
        const pp_index = participator.findIndex(pp => pp === consecrated)
        if (pp_index >= 0) {
            participator.splice(pp_index, 1)
        }
        const winningResult = {
            name: nameOfTheAward,
            consecrated: consecrated,
            total: total,
            frequency: frequency,
            winners: []
        }
        let start_frequency = 1
        otherItemFunc(nameOfTheAward, start_frequency, frequency, consecrated, total, winningResult);
    })
}